# -*- coding: utf-8 -*-

'''
/**
 * @addtogroup txt_filter
 * txt_filter
 * @{
 */
/**
 * @file        txt_filter.py
 * @brief       XXXX
 * @note        XXXX
 * @author      靳普诏(puzhao.jin@hopechart.com)
 * @date        2024/04/23
 * @version     1.0

 * @par         修改日志
 * <table>
 * <tr><th>Date         <th>Version     <th>Author      <th> Description
 * <tr><td>2024/04/23   <td>1.0         <td>靳普诏       <td> 创建初始版本
 * @copyright   xxxx
 */
'''

import sys
import os

## 获取当前脚本所在的目录
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
# 输出目录路径
# print("SCRIPT_DIR: "+ SCRIPT_DIR)

import argparse
import chardet

def txt_filter(input_file: str, output_file: str, filter_list: list, f_append_mode: bool = False, with_filename_tag = False):
    """
    筛选日志文件中的关键信息。

    参数:
    input_file: str - 输入文件的路径。
    output_file: str - 输出文件的路径。
    filter_list: list - 要筛选的关键词列表。
    """
    print(f"input_file: {input_file}")
    print(f"output_file: {output_file}")
    print(f"filter_list: {filter_list}")

    # 检测输入文件的编码
    with open(input_file, 'rb') as file:
        raw_data = file.read()
        result = chardet.detect(raw_data)
        encoding = result['encoding']

    # 使用检测到的编码读取文件
    with open(input_file, 'r', encoding=encoding) as file:
        lines = file.readlines()

    # 筛选包含关键词的行
    filtered_lines = [line for line in lines if any(keyword in line for keyword in filter_list)]

    if with_filename_tag:
        filtered_lines = [f"[{os.path.basename(input_file)}]:\t {line}" for line in filtered_lines]

    # 将筛选后的行以UTF-8编码写入输出文件
    if f_append_mode:
        print("append mode")
        with open(output_file, 'a', encoding='utf-8') as file:
            file.writelines(filtered_lines)
    else:    
        with open(output_file, 'w', encoding='utf-8') as file:
            file.writelines(filtered_lines)






if __name__ == "__main__":


    ## 获取脚本传参
    argv = sys.argv
    argc = len(argv)
    # 打印命令行参数
    #for i in range(1, argc):
        #print("参数", i, ":", argv[i])
        
    print("============= BIGEN: txt_filter.py =============")

    # 示例使用函数
    # 设置命令行参数解析器
    parser = argparse.ArgumentParser(description='Filter log file based on keywords.',
                                      epilog='Example: txt_filter input.txt output.txt "error warning" "debug message"')
    parser.add_argument('input_file', type=str, help='Input log file path')
    parser.add_argument('output_file', type=str, help='Output filtered log file path')
    parser.add_argument('filter_list', nargs='+', type=str, help='List of keywords to filter')

    # 解析命令行参数
    args = parser.parse_args()

    # 调用txt_filter函数
    txt_filter(args.input_file, args.output_file, args.filter_list)

    print("============= END: txt_filter.py =============")



## Generated on "2024-04-23 22:39:07" by the tool "gen_hq_file.py >> V20231119" 

